import { useIntersectionObserver, useIntervalFn } from '@vueuse/core'
import { ref } from 'vue'

export const useLazyData = (apiFn) => {
  // 需要
  // 1. 被观察的对象
  // 2. 不同的回调函数
  const targetRef = ref(null)
  const { stop } = useIntersectionObserver(
    targetRef,
    ([{ isIntersecting }], observerElement) => {
      if (isIntersecting) {
        stop()
        // 调用API获取数据
        apiFn()
      }
    },
    {
      threshold: 0
    }
  )
  // 返回dom
  return { targetRef }
}

export function useCountDown (time) {
  const countTime = ref(0)
  const { pause, resume } = useIntervalFn(() => {
    countTime.value--
    if (countTime.value <= 0) {
      pause()
    }
  }, 1000, false)

  function start () {
    countTime.value = time
    resume()
  }
  return {
    countTime,
    start,
    pause
  }
}
